import { FC, useRef, useState, useEffect } from 'react'
import QuestionCard from '@/components/QuestionCard'
import styles from './common.module.scss'
import { Typography, Spin } from 'antd'
import ListSearch from '@/components/ListSearch'
import { useSearchParams } from 'react-router-dom'
import { questionListAPI } from '@/server/question'
import { useRequest, useDebounceFn, useInViewport } from 'ahooks'

const { Title } = Typography

const List: FC = () => {
  const [searchParams] = useSearchParams()
  const loadingDiv = useRef<HTMLDivElement>(null)
  const [isShow] = useInViewport(loadingDiv.current)
  const [page, setPage] = useState(1)
  const [list, setList] = useState<any[]>([])
  const { run: handelScroll } = useDebounceFn(
    () => {
      if (loadingDiv.current === null) return
      if (isShow) {
        getDataList()
      }
    },
    { wait: 500 }
  )
  const { run: getDataList } = useRequest(
    async () => {
      const { data } = await questionListAPI({
        search: searchParams.get('search') || '',
        page,
      })
      return data
    },
    {
      manual: true,
      onSuccess: res => {
        setList(list => [...list, ...res.list])
        setPage(page => page + 1)
      },
    }
  )
  useEffect(() => {
    window.addEventListener('scroll', handelScroll)
    return () => {
      window.removeEventListener('scroll', handelScroll)
    }
  }, [])
  useEffect(() => {
    getDataList()
  }, [])

  return (
    <div className={styles['List']}>
      <Title level={3} className={styles['List-header']}>
        <div className={styles.left}>我的问卷</div>
        <div className={styles.right}>
          <ListSearch />
        </div>
      </Title>
      <div className={styles['List-content']}>
        {list.map((item: any) => {
          return <QuestionCard key={item._id} {...item} />
        })}
      </div>
      <div ref={loadingDiv} style={{ textAlign: 'center' }}>
        <div style={{ textAlign: 'center' }}>
          <Spin />
        </div>
      </div>
    </div>
  )
}

export default List
